import { findCart, getNewCartGoods, mergeLocalCart, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'
// 合并购物车
// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  mutations: {
    // 设置购物车列表
    setCartList (state, list) {
      state.list = list
    },
    updateCart (state, goods) {
      const obj = state.list.find(item => item.skuId === goods.skuId)
      if (!obj) return
      for (const key in goods) {
        if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
          obj[key] = goods[key]
        }
      }
    },
    // 加入购物车
    insertCart (state, payload) {
      const index = state.list.findIndex(item => item.skuId === payload.skuId)
      if (index === -1) {
        state.list.unshift(payload)
      } else {
        state.list[index].count += payload.count
      }
    },
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    }

  },
  actions: {
    async mergeLocalCart (store) {
      const cartList = store.state.list.map(({ skuId, selected, count }) => ({ skuId, selected, count }))
      await mergeLocalCart(cartList)
      const { result } = await findCart
      store.commit('setCartList', result)
    },
    updateCartSku (store, { oldSkuId, newSkuObj }) {
      console.log(oldSkuId, newSkuObj)
      const oldSkuObj = store.state.list.find(item => item.skuId === oldSkuId)
      if (store.rootState.user.profile.token) {
        deleteCart([oldSkuId]).then(() => {
          insertCart({ skuId: newSkuObj.skuId, count: oldSkuObj.count }).then(() => {
            store.dispatch('findCartList')
          })
        })
      } else {
        store.commit('deleteCart', oldSkuId)
        const { price: nowPrice, inventory: stock, oldPrice: price, skuId, attrsText } = newSkuObj
        store.commit('insertCart', { ...oldSkuObj, nowPrice, stock, price, skuId, attrsText })
      }
    },
    // 删除选中商品
    batchDeleteCart (store) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          console.log('登录状态')
          const arr = store.getters.selectedList.map((item) => item.skuId)
          // store.getters.selectedList.forEach(item => {
          //   arr.push(item.skuId)
          // })
          deleteCart(arr).then(() => {
            store.dispatch('findCartList')
          })
          // console.log(arr)
        } else {
          store.getters.selectedList.forEach(item => {
            store.commit('deleteCart', item.skuId)
          })
          resolve('本地')
        }
      })
    },
    // 全选和反选
    checkAllBtn  (store, selected) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          console.log('登录状态')
          const arr = store.state.list.map((item) => item.skuId)
          // console.log(selected, arr)
          checkAllCart({ selected, arr }).then(() => {
            store.dispatch('findCartList')
          })
        } else {
          store.getters.validList.forEach(item => {
            item.selected = selected
            store.commit('updateCart', item)
          })
          store.commit('checkAllBtn', selected)
          resolve('本地')
        }
      })
    },
    // 更新购物车状态
    updateCart (store, goods) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          console.log('登录状态')
          updateCart(goods).then(() => {
            store.dispatch('findCartList')
          })
        } else {
          store.commit('updateCart', goods)
          resolve('本地')
        }
      })
    },
    // 获取所有购物车列表
    findCartList  (store) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          console.log('登录状态')
          findCart().then(({ result }) => {
            store.commit('setCartList', result)
            resolve('获取购物车成功-线上')
          })
        } else {
          store.state.list.forEach(async item => {
            // 进行遍历，拿到所有新的商品信息
            const { result } = await getNewCartGoods(item.skuId)
            // 更新商品
            store.commit('updateCart', { ...result, skuId: item.skuId })
          })
          resolve('本地')
        }
      })
    },
    // 加入购物车
    insertCart (store, payload) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          console.log('登录状态')
          insertCart(payload).then(() => {
            store.dispatch('findCartList')
          })
        } else {
          store.commit('insertCart', payload)
          resolve('加入购物车成功-本地')
        }
      })
    },
    //
    deleteCart (store, payload) {
      return new Promise((resolve) => {
        if (store.rootState.user.profile.token) {
          deleteCart([payload]).then(() => {
            store.dispatch('findCartList')
          })
          console.log('线上删除', payload)
        } else {
          store.commit('deleteCart', payload)
          resolve('删除商品成功-本地')
        }
      })
    }
  },
  getters: {
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100
    },
    // 有效商品列表
    validList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品件数
    validTotal (state, getters) {
      return getters.validList.reduce((p, i) => i.count + p, 0)
    },
    // 是否全选
    isCheckAll (state, getters) {
      return getters.selectedList.length !== 0 && getters.validList.length === getters.selectedList.length
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) / 100
    }
  }
}
